package com.nq.activaity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nq.activaity.dto.UserTaskResp;
import com.nq.activaity.entity.StIntegralTask;
import com.nq.activaity.entity.StUserIntegralRecord;
import com.nq.activaity.service.IStIntegralTaskService;
import com.nq.common.ServerResponse;
import com.nq.common.State;
import com.nq.dao.activaity.StIntegralTaskMapper;
import com.nq.dao.activaity.StUserIntegralRecordMapper;
import com.nq.pojo.User;
import com.nq.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 积分任务表
 * @Author: jeecg-boot
 * @Date:   2024-11-07
 * @Version: V1.0
 */
@Service
public class StIntegralTaskServiceImpl extends ServiceImpl<StIntegralTaskMapper, StIntegralTask> implements IStIntegralTaskService {


    @Resource
    private IUserService iUserService;
    @Resource
    private StUserIntegralRecordMapper userIntegralRecordMapper;

    @Override
    public ServerResponse taskList(HttpServletRequest request) {
        User user = this.iUserService.getCurrentRefreshUser(request);
        if (null == user) {
            return ServerResponse.createByErrorMsg("User information does not exist !");
        }

        QueryWrapper<StIntegralTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", State.STATE_0);
        List<StIntegralTask> stIntegralTasks = baseMapper.selectList(queryWrapper);

        ArrayList<UserTaskResp> userTaskList = new ArrayList<UserTaskResp>();

        // 查询当前用户完成任务的情况
        for (StIntegralTask task : stIntegralTasks) {
            Integer taskId = task.getId();
            String taskType = task.getTaskType();
            List<StUserIntegralRecord> list = userIntegralRecordMapper.queryListByTaskType(taskType, user.getId(), taskId);
            UserTaskResp taskResp = new UserTaskResp();
            taskResp.setMaxNum(task.getMaxNum());
            taskResp.setTaskName(task.getTaskName());
            taskResp.setTaskType(task.getTaskType());
            taskResp.setIntegral(task.getIntegral());
            taskResp.setCompletionStatus(list.isEmpty() ? 0 : 1);
            taskResp.setRecordList(list);

            userTaskList.add(taskResp);
        }

        return ServerResponse.createBySuccess(userTaskList);
    }
}
